'use strict';

const sanitize = require('sanitize-html');
const url = require('url');

module.exports = (app) => {
  const config = app.config.view.client;
  const apiBase = '/_api/';
  const opts = {
    baseUrl: '/',
    locals: {
      API_BASE: apiBase,
      CALL_INSTANCE_ID: app.config.call.clientInstanceId,
      BAIDU_TONGJI_CODE: app.config.baiduTongjiCode,
      STORE_LOGINNAME: app.config.store.loginName || '',
      STORE_HOSPITALID: app.config.store.hospitalId,
    },
    oss: config.oss,
  };
  let viewIndexMiddleware;
  console.log('config.devServer:', config.devServer); // 值为： http://localhost:3000/
  console.log('config.path:', config.path); //值为： D:\wh\crm-web\client\build
  console.log('opts:', opts);
  if (config.devServer) {
    const serve = require('@wanhu/koa-serve-spa/dev-proxy');
    viewIndexMiddleware = serve(config.devServer, opts);
  } else if (config.path) {
    const serve = require('@wanhu/koa-serve-spa');
    viewIndexMiddleware = serve(config.path, opts);
  }

  class HomeController extends app.Controller {
    async index(ctx) {
      await viewIndexMiddleware(ctx);
    }

    changePassword(ctx) {
      ctx.redirect(
        url.resolve(
          app.config.auth.client.authorizationUri,
          `/modifyPassword?username=${ctx.query.username}&r=${encodeURIComponent(ctx.query.r)}`,
        ),
      );
    }

    async proxyUser(ctx) {
      const target = ctx.url.slice(apiBase.length);
      await ctx.api.user.proxy(target);
    }

    async proxyOld(ctx) {
      const target = ctx.url.slice(apiBase.length);
      await ctx.api.old.proxy(target);
    }

    async proxyTask(ctx) {
      const target = ctx.url.slice(apiBase.length);
      await ctx.api.task.proxy(target);
    }

    async proxyWeixin(ctx) {
      const target = ctx.url.slice(apiBase.length + 7 /*"weixin/".length*/);
      await ctx.api.weixin.proxy(target);
    }

    async proxyPortal(ctx) {
      const target = ctx.url.slice(apiBase.length);
      let result = await ctx.api.portal.proxy(target);
      ctx.cookies.set('token', ctx.session.auth.client.access_token, {
        httpOnly: false,
        signed: false,
        secure: false,
      });
      return result;
    }

    async prePhysicalQuestionnaire(ctx) {
      const { patientId } = ctx.params;
      const body = await ctx.parseBody();
      const data = await ctx.api.portalJson.post(`patients/${patientId}/prePhysicalQuestionnaire`, {
        ...body,
        anamnesisList: JSON.parse(body.anamnesisList),
        fdrsCancerList: JSON.parse(body.fdrsCancerList),
        secondDegreeRelativeCancerList: JSON.parse(body.secondDegreeRelativeCancerList),
      });
      ctx.body = {
        code: 0,
        data,
      };
    }

    // 通用json转发
    async proxyPortalJson(ctx) {
      const curl = ctx.params[0]; // 转发api地址
      const params = await ctx.parseBody();
      let body = [];
      if (params !== '[]') {
        body = JSON.parse(params.data); // data数据
      }
      try {
        const data = await ctx.api.portalJson.post(curl, body);
        ctx.body = {
          code: 0,
          data,
        };
      } catch (error) {
        console.log(error);
      }
    }
    async proxyPortalJsonCall(ctx) {
      const params = await ctx.parseBody();
      const data = await ctx.api.portalJson.post(`sobotCallRecord`, {
        ...params,
      });
      ctx.body = {
        code: 0,
        data: data || true,
      };
    }

    async proxySysConfTags(ctx) {
      const data = await ctx.api.old.get('/sys/conf/tags', ctx.query);
      const withPinyin = data.map(
        (tag) =>
          tag &&
          Object.assign({}, tag, {
            key: ctx.service.helper.pinyin.convertFullPinyin(tag.name),
            group:
              tag.group &&
              Object.assign({}, tag.group, {
                key: ctx.service.helper.pinyin.convertFullPinyin(tag.group.name),
              }),
          }),
      );
      ctx.body = {
        code: 0,
        data: withPinyin,
      };
    }

    async proxySysVersionInsLatest(ctx) {
      const data = await ctx.api.old.get('/sys/versionIns/latest', ctx.query);
      data.insContent = data.insContent && sanitize(data.insContent);
      ctx.body = {
        code: 0,
        data: data,
      };
    }

    async uploadImages(ctx) {
      const body = await ctx.parseBody();
      const data = await ctx.api.portal.post('/uploadImages', { ...body, file: undefined });
      ctx.body = {
        code: 0,
        data,
      };
    }

    async hdDiseases(ctx) {
      ctx.body = {
        code: 0,
        data: {
          anamnesis: [
            {
              icd10: 'code-01',
              title: '既往病史名称1',
              isShow: 1, //是否展示在页面上
              isEmphasis: 1, //是否重点
            },
            {
              icd10: 'code-02',
              title: '既往病史名称2',
              isShow: 1, //是否展示在页面上
              isEmphasis: 1, //是否重点
            },
            {
              icd10: 'code-03',
              title: '既往病史名称3',
              isShow: 1, //是否展示在页面上
              isEmphasis: 1, //是否重点
            },
            {
              icd10: 'code-04',
              title: '既往病史名称4',
              isShow: 1, //是否展示在页面上
              isEmphasis: 1, //是否重点
            },
            {
              icd10: 'code-05',
              title: '既往病史名称5',
              isShow: 1, //是否展示在页面上
              isEmphasis: 0, //是否重点
            },
            {
              icd10: 'code-06',
              title: '既往病史名称6',
              isShow: 1, //是否展示在页面上
              isEmphasis: 0, //是否重点
            },
            {
              icd10: 'code-07',
              title: '既往病史名称7',
              isShow: 0, //是否展示在页面上
              isEmphasis: 1, //是否重点
            },
          ],
          cancer: [
            {
              icd10: 'code-001',
              title: '癌症名称1',
            },
            {
              icd10: 'code-002',
              title: '癌症名称2',
            },
            {
              icd10: 'code-003',
              title: '癌症名称3',
            },
          ],
        },
      };
    }
    async thirdPartyOrders(ctx) {
      const orderList = [];
      ctx.body = {
        code: 0,
        data: [
          {
            orderId: '4324324234',
            orderDate: '2019-07-08',
            hospitalName: '机构名称',
            doctorName: '医生姓名',
            allergies: '过敏史',
            diseases: [
              {
                id: '1b88fcb160444d8883390b81a6ccc449',
                name: '糖尿病',
              },
            ],
            drugs: [
              {
                id: 231,
                amount: 2, //数量,
                useAmount: 5, //单次用量
                frequency: '1', //频次
                commonName: '通用名',
                producerName: '生产厂家',
                productCode: '商品编码',
                productName: '商品名',
                preparationUnit: '20mg', //剂量
                packageSize: '48', //包装规格量
                minimumUnit: '片', //最小使用单位
                packageUnit: '盒', //包装单位
                priceCent: 1200, //单价，以分为单位的整数
                whScale: 20, //报销比例 以百分之一为单位的整数
              },
            ],
          },
          {
            orderId: '43243244423411111',
            hospitalName: '机构名称',
            orderDate: '2019-07-08',
            doctorName: '医生姓名',
            allergies: '过敏史',
            diseases: [
              {
                id: '1b88fcb160444d8883390b81a6ccc449',
                name: '糖尿病',
              },
            ],
            drugs: [
              {
                id: 200,
                amount: 7, //数量,
                useAmount: 1, //单次用量
                frequency: '2', //频次
                commonName: '通用名3',
                producerName: '生产厂家3',
                productCode: '商品编码3',
                productName: '商品名4',
                preparationUnit: '20mg4', //剂量
                packageSize: '48', //包装规格量
                minimumUnit: '片', //最小使用单位
                packageUnit: '盒', //包装单位
                priceCent: 3400, //单价，以分为单位的整数
                whScale: 10, //报销比例 以百分之一为单位的整数
              },
            ],
          },
        ],
      };
    }

    // 健康档案更新转发 json转发
    async physicalExaminationPut(ctx) {
      const { id } = ctx.params;
      const params = await ctx.parseBody();
      let body = [];
      if (params !== '[]') {
        body = JSON.parse(params.data); // data数据
      }
      try {
        const data = await ctx.api.portalJson.put(`patients/physicalExamination/${id}`, { ...body });
        ctx.body = {
          code: 0,
          data,
        };
      } catch (error) {
        console.log('健康档案编辑或者保存报错', error);
        if (error.status === 403) {
          ctx.body = {
            code: 1000,
            message: '抱歉，您没有编辑权限',
          };
        }
      }
    }
    // 健康档案新增转发 json转发
    async physicalExaminationPost(ctx) {
      const { patientId } = ctx.params;
      const params = await ctx.parseBody();
      let body = [];
      if (params !== '[]') {
        body = JSON.parse(params.data); // data数据
      }
      try {
        const data = await ctx.api.portalJson.post(`patients/${patientId}/physicalExamination`, { ...body });
        ctx.body = {
          code: 0,
          data,
        };
      } catch (error) {
        console.log(error);
      }
    }
  }
  return HomeController;
};
